import { getMetadataArgsStorage, MetadataArgsStorage } from 'routing-controllers';
import { PERM_KEY } from '@/decorators/perm.decorator';
import { API_PREFIX } from '@config';
import { ActionMetadataArgs } from 'routing-controllers/types/metadata/args/ActionMetadataArgs';

export interface ApiDoc {
  method: string;
  path: string;
  permCode: string | null;
  handler: string; // 类名.方法名
}

export function getPermissionMetaData(storage: MetadataArgsStorage, action: ActionMetadataArgs): ApiDoc {
  const ctrl = action.target;
  const method = action.type;

  const route = action.route && typeof action.route === 'string' && action.route.startsWith('/') ? action.route : `/${action.route || ''}`;

  const controllerMeta = storage.controllers.find(c => c.target === ctrl);
  const prefix =
    controllerMeta?.route && typeof controllerMeta.route === 'string' && controllerMeta.route.startsWith('/')
      ? controllerMeta.route
      : `/${controllerMeta?.route || ''}`;
  const fullPath = API_PREFIX + prefix + route;

  const handler = `${ctrl.name}.${action.method}`;
  const permCode: string | undefined = Reflect.getMetadata(PERM_KEY, ctrl.prototype, action.method);
  return { method, path: fullPath, permCode, handler };
}

export function scanRoutes(): ApiDoc[] {
  const storage = getMetadataArgsStorage();
  const docs: ApiDoc[] = [];

  for (const action of storage.actions) {
    const { method, path, permCode, handler } = getPermissionMetaData(storage, action);
    docs.push({ method, path, permCode: permCode ?? null, handler });
  }
  return docs;
}
